package com.xb.service.imp;

import com.xb.entity.MedicalExamination;
import com.xb.entity.OutpatientQueue;
import com.xb.entity.Register;
import com.xb.entity.User;
import com.xb.mapper.MedicalExaminationMapper;
import com.xb.mapper.OutpatientQueueMapper;
import com.xb.mapper.RegisterMapper;
import com.xb.mapper.UserMapper;
import com.xb.service.IMedicalExaminationService;
import com.xb.util.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * entityService业务层处理
 */
@Service
public class MedicalExaminationServiceImp implements IMedicalExaminationService {
    @Resource
    private MedicalExaminationMapper medicalExaminationMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private OutpatientQueueMapper outpatientQueueMapper;
    @Resource
    private RegisterMapper registerMapper;


    @Transactional
    @Override
    public Result saveMedicalExaminationInfo(MedicalExamination medicalExamination, HttpSession session) {
        Result result = new Result();
        try {
            medicalExaminationMapper.updateMedicalExamination(medicalExamination);
            OutpatientQueue outpatientQueue = new OutpatientQueue();
            String email = (String) session.getAttribute("email");
            User user = userMapper.selectUserByEmail(email);
            outpatientQueue.setUserId(user.getId());
            outpatientQueue.setPatientId(medicalExamination.getCardId());
            outpatientQueue.setStatus(0);
            if (outpatientQueueMapper.updateStatus(outpatientQueue) == 0) {
                throw new RuntimeException("你没有该权限！");
            }
            Register register = new Register();
            register.setDoctorId(user.getId());
            register.setPatientId(medicalExamination.getCardId());
            if (registerMapper.updateRegisterStatus(register) == 0) {
                throw new RuntimeException("你没有该权限！");
            }
            result.setStatus(Result.RESPONSE_SUCCESS);
            return result;
        } catch (RuntimeException e) {
            result.setStatus(Result.RESPONSE_FAIL);
            result.setMessage("你没有该权限！");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        } catch (Exception e) {
            result.setStatus(Result.RESPONSE_EXCEPTION);
            result.setMessage("出错误了！请联系管理员");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
    }
}
